﻿using JunionRobotTaskManager.Models;
using JunionRobotTaskManager.Repository;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Redbus.Interfaces;
using SqlSugar;

namespace JunionRobotTaskManager.Controllers
{
    /// <summary>
    /// 对接口
    /// </summary>
    [ApiController]
    [Route("api/ports/[action]")]
    public class TransferPortController : ControllerBase
    {

        #region  Field
        private readonly ILogger<TransferPortController> _logger;
        private readonly ITransferPortRepository _deliveryRepository;
        private readonly IEventBus _eventBus;
        #endregion

        public TransferPortController(ILogger<TransferPortController> logger,
            ITransferPortRepository portRepository,
            IEventBus eventBus)
        {
            _logger = logger;
            _deliveryRepository = portRepository;
            _eventBus = eventBus;
        }

        #region 创建

        /// <summary>
        /// 创建对接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Create(TransferPort transferPort)
        {

            try
            {
                bool b = await _deliveryRepository.AddAsync(transferPort);
                if (!b)
                    return ApiResultHelper.Error("添加失败!");
                else
                    _eventBus.Publish<BusMessage>(BusMessage.AddCreate("Port", transferPort));

                return ApiResultHelper.Success(transferPort);
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error("添加出错!" + ex.Message);
            }

        }

        [HttpPost]
        public async Task<ActionResult<ApiResult>> Import(List<TransferPort> transferPorts)
        {
            try
            {
                var ids = transferPorts.Select(x => x.Id).ToList();
                var existsId = _deliveryRepository.Query(x => ids.Contains(x.Id)).Select(x => x.Id);
                var upPorts = transferPorts.Where(x => existsId.Contains(x.Id)).ToList();
                var addPorts = transferPorts.Where(x => !existsId.Contains(x.Id)).ToList();

                if (upPorts.Any())
                {
                    if (!await _deliveryRepository.UpdateListAsync(upPorts))
                        return ApiResultHelper.Error("添加失败，服务器发生错误");
                }

                if (addPorts.Any())
                {
                    if (!await _deliveryRepository.AddListAsync(addPorts))
                        return ApiResultHelper.Error("添加失败，服务器发生错误");
                }


                return ApiResultHelper.Success(0);
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"添加出错!服务器发生错误:{ex.Message}");
            }
        }
        #endregion

        #region 更新


        /// <summary>
        /// 更新对接口信息
        /// </summary>
        /// <param name="deviceId">所属设备Id</param>
        /// <param name="portId">对接口Id</param>
        /// <param name="portDto">新的对接口信息</param>
        /// <returns></returns>
        [HttpPut("{portId}")]
        public async Task<ActionResult<ApiResult>> Update(TransferPort transferPort)
        {

            var port = await _deliveryRepository.FindByIdAsync(transferPort.Id);
            if (port == null)
                return ApiResultHelper.Error("没有找到该触发条件");

            bool b = await _deliveryRepository.UpdateEntityAsync(transferPort);
            if (!b)
                return ApiResultHelper.Error("修改失败");
            else
                _eventBus.Publish<BusMessage>(BusMessage.UpdateCreate("Port", transferPort));

            return ApiResultHelper.Success(transferPort);
        }



        /// <summary>
        /// 更新启用对接口
        /// </summary>
        /// <returns></returns>
        [Route("{id}/{enable}")]
        [HttpPatch]
        public async Task<ActionResult<ApiResult>> Enable(string id, bool enable)
        {
            var port = await _deliveryRepository.FindByIdAsync(id);
            port.Enable = enable;

            bool b = await _deliveryRepository.UpdateEntityAsync(port);
            if (!b)
                return ApiResultHelper.Error("修改失败");
            else
                _eventBus.Publish<BusMessage>(BusMessage.UpdateCreate("Ports", port));
            return ApiResultHelper.Success(port);
        }


        #endregion

        #region 删除

        /// <summary>
        /// 删除对接口
        /// </summary>
        /// <param name="deviceId">所属设备的Id</param>
        /// <param name="id">对接口Id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResult>> Delete( string id)
        {
            bool b = await _deliveryRepository.DeleteByIdAsync(id);
            if (!b) 
                return ApiResultHelper.Error("删除失败");
            else
                _eventBus.Publish<BusMessage>(BusMessage.DeleteCreate("Port",  new string[] { id }));
            
               
            return ApiResultHelper.Success(b);
        }

        /// <summary>
        /// 批量删除对接口
        /// </summary>
        /// <param name="ids">要删除的对接口ids</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<ApiResult>> DeleteByIds(string[] ids)
        {
            bool b = await _deliveryRepository.DeleteByIdsAsync(ids);
            if (!b) 
                return ApiResultHelper.Error("删除失败");
            else
            {
                _eventBus.Publish<BusMessage>(BusMessage.DeleteCreate("Port",  ids));
            }
            return ApiResultHelper.Success(b);
        }

        #endregion

        #region 查找

        /// <summary>
        /// 分页查找对接口信息
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页大小</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetPortsByPage(int page, int limit, [FromQuery] string query)
        {
            RefAsync<int> total = 0;
            try
            {
                if (query != null)
                {
                    JObject jobject = JObject.Parse(query);
                    List<IConditionalModel> models = new List<IConditionalModel>();
                    foreach (var key in jobject.Properties())
                    {
                         models.Add(new ConditionalModel()
                        { FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Equal });
                    }
                    var ports = await _deliveryRepository.QueryAsync(models, page, limit, total);
                 
                    return ApiResultHelper.Success(ports, total);
                }
                else
                {
                    var ports = await _deliveryRepository.QueryAsync(page, limit, total);
                    return ApiResultHelper.Success(ports, total);
                }
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"查询出错:{ex.Message}");
            }
        }

        /// <summary>
        /// 是否存在料口
        /// </summary>
        /// <returns></returns>
        [HttpGet("{query}")]
        public async Task<ActionResult<ApiResult>> Check(string query)
        {
            string currentmsg = query.Split('=', StringSplitOptions.None)[1];
            try
            {
                if (query.Contains("id"))
                {
                    var data = await _deliveryRepository.QueryAsync(x => x.Id == currentmsg);
                    return ApiResultHelper.Success(data.Count);
                }
                else
                {
                    return ApiResultHelper.Error("查询字符串不对");
                }

            }
            catch (Exception e)
            {
                return ApiResultHelper.Error("查找料口出错" + e.Message);
            }

        }

        /// <summary>
        /// 获取所有的对接口信息
        /// </summary>
        /// <returns></returns>
        [Route("api/ports/GetAll")]
        [HttpGet]
        public async Task<ApiResult> GetAll()
        {
            var ports = await _deliveryRepository.QueryAsync();
            return ApiResultHelper.Success(ports);
        }

        #endregion

    }
}
